package com.goodwilldd.base.repository.support.impl;

import java.util.List;

import javax.annotation.PostConstruct;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.data.jpa.repository.support.JpaEntityInformation;
import org.springframework.data.jpa.repository.support.JpaMetamodelEntityInformation;
import org.springframework.data.jpa.repository.support.QueryDslJpaRepository;
import org.springframework.stereotype.Repository;

import com.goodwilldd.base.entities.Person;
import com.goodwilldd.base.entities.QPerson;
import com.goodwilldd.base.repository.support.PersonRepositorySupport;
import com.mysema.query.types.Predicate;

@Repository
public class PersonRepositorySupportImpl implements PersonRepositorySupport {

	@PersistenceContext
	private EntityManager entityManager;

	private QueryDslJpaRepository<Person, Long> repository;

	@PostConstruct
    public void init() {
        JpaEntityInformation<Person, Long> personEntityInfo = new JpaMetamodelEntityInformation<Person, Long>(Person.class, entityManager.getMetamodel());
        repository = new QueryDslJpaRepository<Person, Long>(personEntityInfo, entityManager);
    }
	
	@Override
	public List<Person> findByLastNameIgnoreCase(String searchTerm) {
		return repository.findAll(lastNameIsLike(searchTerm));
	}
	
	private static Predicate lastNameIsLike(final String searchTerm) {
        QPerson person = QPerson.person;
        return person.lastName.startsWithIgnoreCase(searchTerm);
    }

}
